package nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * 聊天室
 * 客户端代码
 */
public class ChatClient {
    public void startClient(String name) throws IOException {
        // 连接服务端
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9090));
        // 接收服务器响应数据
        Selector selector = Selector.open();
        socketChannel.configureBlocking(false);
        // 将通道注册到选择器上
        socketChannel.register(selector, SelectionKey.OP_READ);

        // 创建线程来接收服务端的响应信息
        new Thread(new ClientThread(selector)).start();

        // 向服务端发送信息
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String msg = scanner.nextLine();
            if (msg.length() > 0) {
                socketChannel.write(Charset.forName("UTF-8").encode(name+":"+msg));
            }
        }

    }
}
